import socket
import select
from urllib.request import urlopen
from socketserver import TCPServer, StreamRequestHandler

def socket_server():
    #创建socket
    s = socket.socket()
    #获取主机名
    host = socket.gethostname()
    #端口号
    port = 9999
    print("host: ", host, " port: ", port)

    #绑定服务器地址
    s.bind((host, port))
    #最多可连接的数量
    s.listen(5)

    while True:
        # 阻塞等待连接
        c, addr = s.accept()
        print("Got connection from: ", addr)
        # 发送数据
        c.send("Thank you for coonnecting".encode("utf-8"))
        # 关闭连接
        c.close()



class Handler(StreamRequestHandler):
    def handle(self):
        addr = self.request.getpeername()
        print("Got connection from", addr)
        self.wfile.write(b"Thank you for connecting")


def socket_server():
    server = TCPServer(('', 9999), Handler)
    server.serve_forever()


#使用select创建的服务器
def socket_server_select():
    s = socket.socket()
    host = socket.gethostname()
    port = 9999
    s.bind((host, port))
    s.listen(5)

    inputs = [s]
    while True:
        rs, ws, es = select.select(inputs, [], [])
        for r in rs:
            if r is s:
                c, addr = s.accept()
                print("Got connection from", addr)
                inputs.append(c)
            else:
                try:
                    data = r.recv(1024)
                    disconnect = not data
                except socket.error:
                    disconnect = True

                if disconnect:
                    print(r.getpeername(), " disconnect")
                    inputs.remove(r)
                else:
                    print(data)



def socket_server_poll():
    s = socket.socket()
    host = socket.gethostname()
    port = 9999
    s.bind((host, port))
    s.listen(5)
    
    p = select.poll()
    p.register(s.fileno())

    fdmap = {s.fileno() : s}
    while True:
        events = p.poll()
        for fd, event in events:
            if (fd is s.fileno()) and (event & select.POLLIN):
                c, addr = s.accept()
                print("Got connection from", addr)
                p.register(c)
                fdmap[c.fileno()] = c

            elif event & select.POLLIN:
                data = fdmap[fd].recv(1024)
                if not data:
                    print(fdmap[fd].getpeername(), " disconnect")
                    p.unregister(fd)
                    del fdmap[fd]
                else:
                    print(data)






















